import { useEffect, useState } from "react";
import axios from "../../axios";
import "../../assets/css/Console.scss"
import AutoChart from "../../components/AutoChart"
import { Col, Flex, Row, Divider, Badge, Radio, Tabs, Button, DatePicker } from 'antd';
const { RangePicker } = DatePicker;
import * as  echarts from 'echarts';

function Console() {
    // 销售额  用户访问  订单量  新增用户  请求——————————————————————
    const getsales = async () => {
        localStorage.getItem("token")
        let res = await axios.get("/statistics/home/index", {
            params: {
                temp: new Date().getTime()
            }
        })
        // console.log(res);
        setsales(res)
    }
    const [sales, setsales] = useState({})
    const [operating, setoperating] = useState({})
    // 经营数据开始了------------------------------
    const getoperating = async () => {
        let res = await axios.get("/statistics/home/operating/data", {
            params: {
                temp: new Date().getTime()
            }
        })
        setoperating(res)
    }

    // 订单统计 开始了***************************************
    const [day, setDay] = useState('yesterday');//天数切换效果

    const [dayobj, setDayobj] = useState({})

    const getStatistics = async (dateLimit) => {
        let res = await axios.get("/statistics/user/overview", {
            params: {
                dateLimit,
                temp: new Date().getTime()
            }
        })
        // console.log(res);
        setDayobj(res)
    }
    const onChange = (e) => {

        setDay(e.target.value);

        getStatistics(e.target.value)
    };
    const [placement, setPlacement] = useState('');
    const onChangetime = (e) => {
        if (!e) {
            setPlacement("")
            return false
        }
        const startTime = `${e[0].$y}-${(e[0].$M + 1) < 10 ? "0" + (e[0].$M + 1) : (e[0].$M + 1)}-${(e[0].$D) < 10 ? "0" + (e[0].$D) : (e[0].$D)}`;
        const endTime = `${e[1].$y}-${(e[1].$M + 1) < 10 ? "0" + (e[1].$M + 1) : (e[1].$M + 1)}-${(e[1].$D) < 10 ? "0" + (e[1].$D) : (e[1].$D)}`;
        // console.log(`${e[1].$y}-${(e[1].$M+1}-${e[1].$D}`);

        setPlacement(`${startTime},${endTime}`);
        // getStatistics(`${startTime},${endTime}`)
    };
    const searchTime = () => {
        if (placement !== "") {

            getStatistics(placement)
        }
    }
    // 订单统计 end***************************************


    const [timeval, setTimeval] = useState("day")
    const [option, setOption] = useState({
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '2%',
            orient: 'vertical',
            right: 'right'
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: ['30%', '50%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 40,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    // { value: 1048, name: 'H5' },
                    // { value: 735, name: 'app' },
                    // { value: 580, name: '小程序' },
                ]
            }
        ]
    })
    const getOption = async () => {

        let res = await axios.get("/statistics/user/channel", {
            params: {
                temp: new Date().getTime()
            }

        })
        const data = []
        res.map(item => {
            data.push({
                value: item.num,
                name: item.channel
            })
            setOption(pre => {
                // console.log(pre);
                pre.series[0].data = data
                return { ...pre }
            })
        })
    }
    // ***************************************************************222222222222222222222222
    const [option2, setOption2] = useState({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },

        legend: {
            data: []
        },
        xAxis: [
            {
                type: 'category',
                data: [],// 存放日期
                axisPointer: {
                    type: 'shadow'
                },
                axisLabel: {
                    rotate: 45 // X轴标签倾斜 45 度
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '订单金额',
                // min: 0,
                // max: 250,
                // interval: 50,
                axisLabel: {
                    formatter: '{value}'
                }
            },
            {
                type: 'value',
                name: '订单数量',
                // min: 0,
                // max: 25,
                // interval: 5,
                axisLabel: {
                    formatter: '{value}'
                }
            }
        ],
        series:[]
    })
    const getoption2 = async () => {
        let res = await axios.get("/statistics/home/chart/order", { params: { temp: new Date().getTime() } })
        let date = []
        let ordermoney = []
        let ordernum = []
        for (const key in res.price) {
            date.push(key)
            ordermoney.push(res.price[key])
        }
        for (const key in res.quality) {
            ordernum.push(res.quality[key])
        }
        // console.log(ordernum);
        setOption2(pre => {
            pre.legend.data=['订单金额','订单数量']
            pre.xAxis[0].data = date;
            // pre.series[0].data=ordermoney;
            // pre.series[1].data=ordernum
            pre.series = [

                {
                    name: '订单金额',
                    type: 'bar',
                    tooltip: {
                        valueFormatter: function (value) {
                            return '￥' + value;
                        }
                    },
                    data: ordermoney
                },
                {
                    name: '订单数量',
                    type: 'line',
                    yAxisIndex: 1,
                    tooltip: {
                        valueFormatter: function (value) {
                            return value + '个';
                        }
                    },
                    data: ordernum
                }
            ]
            return { ...pre }
        })
    }
    const showFour =async (arg)=>{
        let res=await axios.get(`/statistics/home/chart/order/${arg}`,{ params: { temp: new Date().getTime() } })
        let week=[]
        let preweekdata=[]
        let weekdata=[]
        let preordernum=[]
        let ordernum=[]
        for (const key in res.prePrice) {
            week.push(key)
            preweekdata.push(res.prePrice[key])
            
        }
        for (const key in res.price) {
            weekdata.push(res.price[key])
        }
        for (const key in res.preQuality) {
            preordernum.push(res.preQuality[key])
        }
        for (const key in res.quality) {
            ordernum.push(res.quality[key])
        }
        setOption2(pre=>{
            pre.xAxis[0].data=week;
            pre.legend.data=['上周金额','本周金额','上周订单数','本周订单数']
            pre.series=[
                    {
                      name: '上周金额',
                      type: 'bar',
                      tooltip: {
                        valueFormatter: function (value) {
                          return value;
                        }
                      },
                      data:preweekdata
                    },
                    {
                      name: '本周金额',
                      type: 'bar',
                      tooltip: {
                        valueFormatter: function (value) {
                          return value ;
                        }
                      },
                      data:weekdata
                    },
                    {
                      name: '上周订单数',
                      type: 'line',
                      yAxisIndex: 1,
                      tooltip: {
                        valueFormatter: function (value) {
                          return value  ;
                        }
                      },
                      data:preordernum
                    },
                    {
                      name: '本周订单数',
                      type: 'line',
                      yAxisIndex: 1,
                      tooltip: {
                        valueFormatter: function (value) {
                          return value  ;
                        }
                      },
                      data:ordernum

                    }
                  ]
            return {...pre}
        })
    }
    const orderonChange = (e) => {
        setTimeval(e.target.value)
        if (e.target.value=="day") {
            getoption2()
        }else{
            showFour(e.target.value)
        }
    }


    const [option3,setOption3]=useState({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'cross',
                  label: {
                    backgroundColor: '#6a7985'
                  }
                }
              },
              legend: {
                data: [""]
              },
              toolbox: {
            
              },
              grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
              },
              xAxis: [
                {
                  type: 'category',
                  boundaryGap: false,
                  data: [],
                  axisLabel: {
                    rotate: 45 // X轴标签倾斜 45 度
                }
                }
                
              ],
              yAxis: [
                {
                  type: 'value'
                }
              ],
              series: [
                {
                  name: '人数',
                  type: 'line',
                  stack: 'Total',
                  smooth: true,
                  lineStyle: {
                    width: 0
                  },
                  showSymbol: false,
                  areaStyle: {
                    opacity: 0.8,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      {
                        offset: 0,
                        color: 'rgb(128, 255, 165)'
                      },
                      {
                        offset: 1,
                        color: 'rgb(1, 191, 236)'
                      }
                    ])
                  },
                  emphasis: {
                    focus: 'series'
                  },
                  data: [140, 232, 101, 264, 90, 340, 250]
                }
              ]
          
    })
    const getoption3=async ()=>{
        let res=await axios.get("/statistics/home/chart/user",{
            temp:new Date().getTime()
        })
        console.log(res);
        let date = []
        let value=[]
        for (const key in res) {
            date.push(key)
            value.push(res[key])
        }
        console.log(date);
        setOption3(pre => {
            pre.xAxis[0].data = date;
        //    console.log(pre);
        console.log(value);
        pre.series[0].data=value
        return {...pre}
        })
    }

    useEffect(() => {
        getsales()// 
        getoperating()//经营数据

        getStatistics(day)// 三角
        getOption()
        getoption2()
        getoption3()
    }, [])







    return (
        <>
            <Row gutter={20}>
                <Col className="colbottom" xs={24} sm={24} md={12} lg={6} xl={6}>
                    <Flex className="whitebg fourdiv" vertical={true} justify="space-between">
                        <Flex justify="space-between">
                            <div>销售额</div>
                            <Badge count={"今日"}></Badge>
                        </Flex>
                        <h1>{sales.sales}</h1>
                        <Divider></Divider>
                        <Flex justify="space-between">
                            <section>昨日数据</section>
                            <section>{sales.yesterdaySales}</section>
                        </Flex>
                    </Flex>
                </Col>
                <Col className="colbottom" xs={24} sm={24} md={12} lg={6} xl={6}>
                    <Flex className="whitebg fourdiv" vertical={true} justify="space-between">
                        <Flex justify="space-between">
                            <div>用户访问量</div>
                            <Badge count={"今日"}></Badge>
                        </Flex>
                        <h1>{sales.pageviews}</h1>
                        <Divider></Divider>
                        <Flex justify="space-between">
                            <section>昨日数据</section>
                            <section>{sales.yesterdayPageviews}</section>
                        </Flex>
                    </Flex>
                </Col>
                <Col className="colbottom" xs={24} sm={24} md={12} lg={6} xl={6}>
                    <Flex className="whitebg fourdiv" vertical={true} justify="space-between">
                        <Flex justify="space-between">
                            <div>订单量</div>
                            <Badge count={"今日"}></Badge>
                        </Flex>
                        <h1>{sales.orderNum}</h1>
                        <Divider></Divider>
                        <Flex justify="space-between">
                            <section>昨日数据</section>
                            <section>{sales.yesterdayOrderNum}</section>
                        </Flex>
                    </Flex>
                </Col>
                <Col className="colbottom" xs={24} sm={24} md={12} lg={6} xl={6}>
                    <Flex className="whitebg fourdiv" vertical={true} justify="space-between">
                        <Flex justify="space-between">
                            <div>新增用户</div>
                            <Badge count={"今日"}></Badge>
                        </Flex>
                        <h1>{sales.newUserNum}</h1>
                        <Divider></Divider>
                        <Flex justify="space-between">
                            <section>昨日数据</section>
                            <section>{sales.yesterdayNewUserNum}</section>
                        </Flex>
                    </Flex>
                </Col>
            </Row>
            <Row gutter={20}>
                <Col className="colbottom" xs={24} sm={24} md={24} lg={24} xl={12}>
                    <section className="whitebg ">
                        <h3>快捷入口</h3>
                        <Flex wrap className="fourdiv">
                            <div className="flexitem">
                                <div className="pic">图标</div>
                                <p>用户管理</p>
                            </div>
                            <div className="flexitem">
                                <div className="pic">图标</div>
                                <p>用户管理</p>
                            </div>
                            <div className="flexitem">
                                <div className="pic">图标</div>
                                <p>用户管理</p>
                            </div>
                            <div className="flexitem">
                                <div className="pic">图标</div>
                                <p>用户管理</p>
                            </div>
                            <div className="flexitem">
                                <div className="pic">图标</div>
                                <p>用户管理</p>
                            </div>
                            <div className="flexitem">
                                <div className="pic">图标</div>
                                <p>用户管理</p>
                            </div>
                        </Flex>
                    </section>
                </Col>
                <Col className="colbottom" xs={24} sm={24} md={24} lg={24} xl={12}>
                    <section className="whitebg ">
                        <h3>经营数据</h3>
                        <Flex wrap className="fourdiv">
                            <div className="flexitem2">
                                <div className="text">{operating.notShippingOrderNum}</div>
                                <p>待发货订单</p>
                            </div>
                            <div className="flexitem2">
                                <div className="text">{operating.refundingOrderNum}</div>
                                <p>退款中订单</p>
                            </div>
                            <div className="flexitem2">
                                <div className="text">{operating.notWriteOffOrderNum}</div>
                                <p >待核销订单</p>
                            </div>
                            <div className="flexitem2">
                                <div className="text">{operating.vigilanceInventoryNum}</div>
                                <p >库存预警</p>
                            </div>
                            <div className="flexitem2">
                                <div className="text">{operating.onSaleProductNum}</div>
                                <p >上架商品</p>
                            </div>
                            <div className="flexitem2">
                                <div className="text">{operating.notSaleProductNum}</div>
                                <p >仓库商品</p>
                            </div>
                            <div className="flexitem2">
                                <div className="text">{operating.notAuditNum}</div>
                                <p >提现待审核</p>
                            </div>
                            <div className="flexitem2">
                                <div className="text">{operating.totalRechargeAmount}</div>
                                <p >账户充值</p>
                            </div>
                            <div className="flexitem2">
                                <div className="text">100</div>
                                <p >用户管理</p>
                            </div>
                        </Flex>
                    </section>
                </Col>
            </Row>
            <Row gutter={20}>
                <Col className="colbottom" xs={24} sm={24} md={24} lg={24} xl={18}>
                    <section className="whitebg">
                        <Flex justify="space-between">
                            <h3>订单统计</h3>
                            <Radio.Group
                                value={day}
                                onChange={onChange}
                                style={{
                                    marginBottom: 16,
                                }}
                            >
                                <Radio.Button value="yesterday">昨天</Radio.Button>
                                <Radio.Button value="lately7">近七天</Radio.Button>
                                <Radio.Button value="lately30">近30天</Radio.Button>
                            </Radio.Group>

                            <RangePicker onChange={(e) => onChangetime(e)} />

                            <Button onClick={() => searchTime()} type="primary">搜索</Button>

                        </Flex>

                        <Flex>
                            <div>
                                <p>注册</p>
                                {/* <p>{dayobj.registerNumRatio}</p> */}
                                <div className="box1">
                                    <div>
                                        <section>  注册用户数量:{dayobj.registerNum}</section>
                                        <section> 环比增长率：{dayobj.registerNumRatio}</section>
                                    </div>
                                    <div className="one column_center">
                                        <div>{dayobj.pageviews}</div>
                                        <div>访客</div>
                                    </div>
                                </div>
                                <div className="box2">
                                    <div>
                                        <section>  活跃用户数量:{dayobj.activeUserNum}</section>
                                        <section> 环比增长率：{dayobj.activeUserNumRatio}</section>
                                    </div>
                                    <div className="two column_center">
                                        <div>{dayobj.orderUserNum}</div>
                                        <div>下单</div>
                                    </div>
                                </div>
                                <div className="box3">
                                    <div className="between">
                                        <div>
                                            <section>  充值用户数量:{dayobj.rechargeUserNum}</section>
                                            <section> 环比增长率：{dayobj.rechargeUserNumRatio}</section>
                                        </div>
                                        <div>
                                            客单价：{dayobj.payOrderAmount}
                                        </div>
                                    </div>
                                    <div className=" three column_center">
                                        <div>{dayobj.orderPayUserNum}
                                            <div>成交用户</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </Flex>
                    </section>

                </Col>
                <Col className="colbottom" xs={24} sm={24} md={24} lg={24} xl={6}>
                    <section className="whitebg" style={{ height: "400px" }}>
                        用户统计
                        <AutoChart option={option}></AutoChart>
                    </section>

                </Col>
            </Row>
            <Row>
                <Col className="colbottom" xs={24} sm={24} md={24} lg={24} xl={24}>
                    <section className="whitebg" style={{ height: "400px" }}>
                        <Flex>
                            <h3> 订单统计</h3>
                            <Radio.Group value={timeval} onChange={orderonChange} style={{ marginBottom: 16 }}>
                                <Radio.Button value="day">30天</Radio.Button>
                                <Radio.Button value="week">周</Radio.Button>
                                <Radio.Button value="month">月</Radio.Button>
                                <Radio.Button value="year">年</Radio.Button>
                            </Radio.Group>
                        </Flex>


                        <AutoChart option={option2}></AutoChart>
                    </section>

                </Col>
            </Row>
            <Row>
                <Col className="colbottom" xs={24} sm={24} md={24} lg={24} xl={24}>
                    <section className="whitebg" style={{ height: "400px" }}>
                        用户统计
                        <AutoChart option={option3}></AutoChart>
                    </section>

                </Col>
            </Row>
        </>

    );
}

export default Console;